package tech.yangzhijie.basic.knowledge.mianshi;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.atomic.AtomicInteger;

public class Test09CyclicBarrier {

    public static void main(String[] args) {
        Goods goods = new Goods();
        CyclicBarrier cyclicBarrier = new CyclicBarrier(3,()->{
            System.out.println(Thread.currentThread().getName() + " 香烟：" + goods.getSmoke().get() + " 可乐：" + goods.getCoke().get() + " " +
                    " 手机：" + goods.getPhone());
        });
        for (int i = 0; i < 3; i++) {
            final int num = i;
            new Thread(()->{
                if(num == 0){
                    goods.getSmoke().getAndAdd(20);
                }else if(num == 1) {
                    goods.getCoke().getAndAdd(10);
                }else {
                    goods.getPhone().getAndAdd(1);
                }
                try {
                    cyclicBarrier.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName());
            }).start();
        }
    }
}

class Goods {
    private AtomicInteger smoke = new AtomicInteger();
    private AtomicInteger coke = new AtomicInteger();
    private AtomicInteger phone = new AtomicInteger();

    public AtomicInteger getSmoke() {
        return smoke;
    }

    public AtomicInteger getCoke() {
        return coke;
    }

    public AtomicInteger getPhone() {
        return phone;
    }
}
